#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
using namespace std;
class Solution {
    int m, n;
    int step = 0;
    bool as[20][20];
    int ret = 0;
public:
    int uniquePathsIII(vector<vector<int>>& grid) {
        m = grid.size();
        n = grid[0].size();
        int x1 = 0;
        int y1 = 0;
        for (int i = 0; i < grid.size(); i++)
        {
            for (int j = 0; j < grid[i].size(); j++)
            {
                if (grid[i][j] == 0)
                {
                    step++;
                }
                if (grid[i][j] == 1)
                {
                    x1 = i;
                    y1 = j;
                }
            }
        }
        step += 2;
        as[x1][y1] = true;
        dfs(grid, x1, y1, 1);
        return ret;
    }
    int dfx[4] = { 0,0,1,-1 };
    int dfy[4] = { 1,-1,0,0 };
    void dfs(vector<vector<int>>& grid, int i, int j, int pos)
    {
        if (grid[i][j] == 2)
        {
            if (pos == step)
            {
                ret++;
            }
            return;
        }
        for (int k = 0; k < 4; k++)
        {
            int x = i + dfx[k];
            int y = j + dfy[k];
            if (x < m && x >= 0 && y >= 0 && y < n && !as[x][y] && grid[x][y] != -1)
            {
                as[x][y] = true;
                dfs(grid, x, y, pos + 1);
                as[x][y] = false;
            }
        }

    }
};